package com.c2b.algorithm.leetcode.base.backtracking;

import java.util.*;

/**
 * <a href='https://leetcode.cn/problems/combination-sum-ii/description/'>组合总和 II(Combination Sum II)</a>
 * <p>给定一个候选人编号的集合 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。</p>
 * <p>candidates 中的每个数字在每个组合中只能使用 一次 。 </p>
 * <p>注意：解集不能包含重复的组合。  </p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1:
 *      输入: candidates = [10,1,2,7,6,1,5], target = 8,
 *      输出:
 *      [
 *      [1,1,6],
 *      [1,2,5],
 *      [1,7],
 *      [2,6]
 *      ]
 *
 * 示例 2:
 *      输入: candidates = [2,5,2,1,2], target = 5,
 *      输出:
 *      [
 *      [1,2,2],
 *      [5]
 *      ]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= candidates.length <= 100</li>
 *         <li>1 <= candidates[i] <= 50</li>
 *         <li>1 <= target <= 30</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/26 16:41
 */
public class LC0040CombinationSum_II_M {
    static class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            List<List<Integer>> retList = new ArrayList<>();
            Arrays.sort(candidates);
            search(candidates, 0, target, new ArrayDeque<>(), retList);
            return retList;
        }

        private void search(int[] candidates, int startPoint, int target, Deque<Integer> path, List<List<Integer>> retList) {
            if (target == 0) {
                retList.add(new ArrayList<>(path));
                return;
            }
            for (int i = startPoint; i < candidates.length; i++) {
                // 大剪枝：减去 candidates[i] 小于 0，减去后面的 candidates[i + 1]、candidates[i + 2] 肯定也小于 0，因此用 break
                if (target - candidates[i] < 0) {
                    break;
                }
                // 小剪枝：同一层相同数值的结点，从第 2 个开始，候选数更少，结果一定发生重复，因此跳过，用 continue
                if (i > startPoint && candidates[i] == candidates[i - 1]) {
                    continue;
                }
                path.add(candidates[i]);
                //System.out.println("递归之前 => " + path + "，剩余 = " + (target - candidates[i]));
                search(candidates, i + 1, target - candidates[i], path, retList);
                path.removeLast();
                //System.out.println("递归之后 => " + path + "，剩余 = " + (target - candidates[i]));
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        for (List<Integer> integerList : solution.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8)) {
            for (Integer integer : integerList) {
                System.out.print(integer + "  ");
            }
            System.out.println();
        }

        for (List<Integer> integerList : solution.combinationSum2(new int[]{2,5,2,1,2}, 5)) {
            for (Integer integer : integerList) {
                System.out.print(integer + "  ");
            }
            System.out.println();
        }
    }
}
